<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { getPageTree } from '@fl/api/advertising-api/page-config'
import type { getPageTreeParam } from '@fl/api/advertising-api/models/page-config-models'
import { ElCard, ElInput, ElTree } from 'element-plus'
import rightBox from './page-list/index.vue'
import { cloneDeep } from 'lodash-es'
import { SubmitBtn } from '@fl/components'
import { nextTick } from 'vue'

const activeTreeId = ref<number>()
const activehandler = ref<string>('')
const activePtagEn = ref<string>('')
const isTrue = ref<boolean>(true)
const isExpandAll = ref<boolean>(false)
const historyVisible = ref<boolean>(false)
const historyTitle = ref<string>('历史版本')
const isLoading = ref<boolean>(false)
const formRef = ref()
const historyList = ref<any>()
const parentTreeId = ref<number>(1) // 首页1，新房12；用于去掉新房的广告组选择
const currentRootPtagEn = ref<string>('') // 当前选中树的根节点 ptagEn
const parentPtagEn = ref<string>('') // 父级 ptagEn

// 左侧树
const treeRef = ref<any>()
const filterText = ref<string>('')
watch(filterText, (val) => {
    treeRef.value!.filter(val)
})
const defaultProps = {
    children: 'lowerPageList',
    label: 'pnameCN',
}
const dataTree = ref<any>()

const initialState = {
    version: undefined,
}
const state = ref<getPageTreeParam>(cloneDeep(initialState))

async function getTreeList(params?: getPageTreeParam) {
    try {
        const res = await getPageTree(params)
        dataTree.value = processTreeData(res)
        console.log('getTreeList', dataTree.value)
        await nextTick()
        activeTreeId.value = dataTree.value[0].lowerPageList[0].id
        activePtagEn.value = dataTree.value[0].lowerPageList[0].ptagEn
        activehandler.value = dataTree.value[0].lowerPageList[0].handler
        console.log('activeTreeId.value', activeTreeId.value)
    }
    catch (error) {

    }
}
getTreeList()

// 将上级ptagEn添加到所有下级，目前只考虑3级
function processTreeData(nodes: any, parentNode?: any) {
    return nodes.map((node) => {
        const newNode = { ...node }
        if (parentNode) {
            // 直接父级 ptagEn
            newNode.parentPtagEn = parentNode.ptagEn
            // 祖父级 ptagEn（如果存在）
            if (parentNode.parentPtagEn) {
                newNode.rootPtagEn = parentNode.parentPtagEn
            }
        }
        // 递归处理子节点
        if (newNode.lowerPageList && newNode.lowerPageList.length > 0) {
            newNode.lowerPageList = processTreeData(newNode.lowerPageList, newNode)
        }
        return newNode
    })
};

async function getTreeHistory(params) {
    isLoading.value = true
    try {
        const res = await getPageTree(params)
        console.log('res', res, dataTree.value)
        historyList.value = res
        isLoading.value = false
    }
    catch (error) {
        isLoading.value = false
    }
}

function filterNode(value: string, data: any) {
    console.log(data, value)
    if (!value)
        return true
    return data.pnameCN.includes(value)
}

function handleNodeClick(row) {
    // 子级添加顶级id（暂注释）
    // const id: number = getTopParentId(row, node, self);
    // parentTreeId.value = id

    if (row.isConfigurable === 0)
        return
    activeTreeId.value = row.id
    activehandler.value = row.handler
    activePtagEn.value = row.ptagEn
    currentRootPtagEn.value = row.rootPtagEn || ''
    parentPtagEn.value = row.parentPtagEn || ''
    console.log('点击左侧树', activeTreeId.value, activePtagEn.value, row)
}

// function getTopParentId(node, parent, Tree) {
//     if (node.parentId !== 0) {
//         // 递归查找顶层父节点
//         const parentNode = treeRef.value.getNode(node.parentId);
//         return getTopParentId(parentNode.data, parentNode, Tree);
//     } else {
//         // 顶层父节点
//         return node.id;
//     }
// }

function getHistoryVersion() {
    state.value.version = undefined
    const params = {
        type: 0,
    }
    getTreeHistory(params)
    historyVisible.value = true
}

function resetVersion() {
    filterText.value = '' // 顺带重置搜索文字
    const params = {}
    getTreeList(params)
}

function cancel() {
    historyVisible.value = false
}

// 选择版本、刷新左侧树
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const target = historyList.value.find(item => state.value.version === item.id)
        const params = {
            maxVersion: target.maxVersion,
            minVersion: target.minVersion,
            pageResourceId: target.id,
        }
        console.log('params', params)
        getTreeList(params)
        cancel()
    }
}

const columns: PlusColumn[] = [
    {
        label: '版本',
        prop: 'version',
    },
]

const rules = {
    version: [
        {
            message: '请选择一个版本',
            required: true,
        },
    ],
}
</script>

<template>
    <div class="body">
        <!-- 一、左侧树 -->
        <ElCard class="tree"
                shadow="never"
        >
            <ElInput v-model="filterText" />

            <div class="mt20 flex"
                 style="justify-content: space-between;"
            >
                <ElButton type="primary"
                          @click="getHistoryVersion"
                >
                    历史版本
                </ElButton>

                <ElButton @click="resetVersion">
                    重置
                </ElButton>
            </div>
            <!-- :default-expanded-keys="['root', 'home']" -->
            <ElTree ref="treeRef"
                    class="role-tree mt20"
                    :data="dataTree"
                    :props="defaultProps"
                    node-key="id"
                    :default-expand-all="isExpandAll"
                    :highlight-current="isTrue"
                    :expand-on-click-node="isTrue"
                    :filter-node-method="filterNode"
                    :current-node-key="activeTreeId"
                    @node-click="handleNodeClick"
            />
        </ElCard>

        <!-- 二、右侧 -->
        <div class="right ml-20">
            <rightBox :active-tree-id="activeTreeId"
                      :active-ptag-en="activePtagEn"
                      :activehandler="activehandler"
                      :parent-tree-id="parentTreeId"
                      :current-root-ptag-en="currentRootPtagEn"
                      :parent-ptag-en="parentPtagEn"
            />
        </div>

        <!-- 历史版本 -->
        <PlusDialog v-model="historyVisible"
                    :title="historyTitle"
                    width="840"
                    close-on-press-escape
                    :has-footer="false"
                    @cancel="cancel"
                    @closed="cancel"
        >
            <ElSkeleton v-if="isLoading"
                        animated
                        class="mt-20"
            />

            <template v-else>
                <div class="plusform mt-20">
                    <PlusForm ref="formRef"
                              v-model="state"
                              :columns="columns"
                              :label-width="120"
                              :rules="rules"
                              :has-footer="false"
                              :row-props="{ gutter: 20 }"
                    >
                        <template #plus-field-version>
                            <el-radio-group v-model="state.version">
                                <el-radio v-for="item in historyList"
                                          :key="item.id"
                                          :label="item.pnameCN"
                                          :value="item.id"
                                          border
                                />
                            </el-radio-group>
                        </template>
                    </plusform>
                </div>

                <div class="mx-auto mt20 flex justify-center">
                    <el-button @click="cancel">
                        取消
                    </el-button>

                    <SubmitBtn type="primary"
                               @click="submit"
                    >
                        提交
                    </SubmitBtn>
                </div>
            </template>
        </PlusDialog>
    </div>
</template>

<style lang="scss" scoped>
.body {
    display: flex;
    flex-direction: row;

    .tree {
        flex: 1;
    }

    .role-tree {
        height: 90vh;
        overflow-y: auto;
    }

    .right {
        flex: 4;
        overflow: auto;
    }
}

:deep(.el-radio.is-bordered) {
    margin-bottom: 20px;
}
</style>
